package com.unicom.wostore.dsp.controller;

import net.sf.json.JSONObject;
import com.unicom.wostore.dsp.utils.HttpUtil;
import com.unicom.wostore.dsp.utils.RedisApi;
import net.sf.json.JSONArray;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Huangjie on 2017/2/23.
 */
@Controller
@RequestMapping("appcoach")
public class AppcoachAction {
    @Autowired
    RedisApi redisApi;

    Logger logger = LoggerFactory.getLogger(AppcoachAction.class);

    static final int STATUS_CODE_SUCCESS = 1;
    static final int STATUS_CODE_NULL = 0;
    static final int STATUS_CODE_DATA_ERROR = -1;
    static final int STATUS_CODE_FAIL = -2;

    static final int MEDIA_BANNER = 1; //Banner



    @RequestMapping(value = "getAds",method = {RequestMethod.POST},consumes = "application/json")
    @ResponseBody
    public JSONObject getAds(@RequestBody JSONObject jsonObj, HttpServletRequest httpServletRequest){

        JSONObject responseJson =new JSONObject();
        try {

            String ipAddr = HttpUtil.getIpAddr(httpServletRequest);

            /**
             * 如果存在数据错误,返回statuscode:-1
             */
            if(!DataValidate(jsonObj)){
                responseJson.put("statuscode",STATUS_CODE_DATA_ERROR);
                return responseJson;
            }

            JSONObject appcoachJson = Transfer2AppcoachJson(jsonObj,ipAddr);

            logger.info("Request Info="+appcoachJson.toString()+"  IP:"+ipAddr);

            JSONObject appcoachResponeJson= HttpUtil.postJson("http://api.appcoachs.net/v1/m/image",appcoachJson,null);

            /**
             * 如果请求没有返回值,返回statuscode:0
             */
            if(appcoachResponeJson==null){
                responseJson.put("statuscode",STATUS_CODE_NULL);
                return responseJson;
            }

            JSONArray resAdsJsonArr = new JSONArray();
            JSONArray adsJsonArr = appcoachResponeJson.getJSONObject("ads").getJSONArray ("ad");

            for (Object adObj : adsJsonArr){
                if(adObj!=null){
                    JSONObject newAdJson = new JSONObject();
                    JSONObject adJson = (JSONObject) adObj;
                    newAdJson.put("img",adJson.getString("image_url"));
                    newAdJson.put("target",adJson.getString("click_url"));
                    newAdJson.put("actiontype",Integer.valueOf(adJson.getString("actionType")));
                    resAdsJsonArr.add(newAdJson);
                }
            }

            responseJson.put("ads",resAdsJsonArr);

            responseJson.put("statuscode",STATUS_CODE_SUCCESS);
            return responseJson;
        }catch (Exception e){
            logger.error(e.getMessage());
            responseJson.put("statuscode",STATUS_CODE_FAIL);
            return responseJson;
        }
    }


    @Value("${appcoach.site.id}")
    private  String appcoachSiteId;

    @Value("${appcoach.site.slotid.320.50}")
    private  int slotId320;

    @Value("${appcoach.site.slotid.640.100}")
    private  int slotId640;



    /**
     * request 数据合法性验证
     * Created by Huangjie on 2017/2/23.
     */
    private Boolean DataValidate(JSONObject jsonObject) {
        if (jsonObject == null)
            return false;

        if (jsonObject.has("display")) {
            JSONArray displayJsonArr =  jsonObject.getJSONArray("display");
            for(int i=0;i<displayJsonArr.size();i++){
                JSONObject displayJson = (JSONObject) displayJsonArr.get(i);
                if (!displayJson.has("media_id") || !(displayJson.get("media_id") instanceof Integer) || StringUtil.isEmpty(displayJson.getString("media_id"))) {
                    return false;
                }
                if (!displayJson.has("size") || StringUtil.isEmpty(displayJson.getString("size"))) {
                    return false;
                }
            }
        } else {
            return false;
        }

        if (jsonObject.has("os")) {
            if (!jsonObject.getJSONObject("os").has("name") || StringUtil.isEmpty(jsonObject.getJSONObject("os").getString("name"))) {
                return false;
            }
            if (!jsonObject.getJSONObject("os").has("version") || StringUtil.isEmpty(jsonObject.getJSONObject("os").getString("version"))) {
                return false;
            }
        } else {
            return false;
        }

        if (jsonObject.has("pkgname")) {
            if (StringUtil.isEmpty(jsonObject.getString("pkgname"))) {
                return false;
            }
        } else {
            return false;
        }

        if (jsonObject.has("sdk_ver")) {
            if (StringUtil.isEmpty(jsonObject.getString("sdk_ver"))) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }


    private JSONObject Transfer2AppcoachJson(JSONObject jsonObject,String ipAddr){
        JSONObject appoachJson = new JSONObject();

        JSONObject siteJson = new JSONObject();
        //siteJson.put("id",appcoachSiteId);
        siteJson.put("id","kepvWLCp");
        appoachJson.put("site",siteJson);

        JSONArray impressionJsonArray = new JSONArray();
        JSONArray displayJsonArr =  jsonObject.getJSONArray("display");
        for(int i=0;i<displayJsonArr.size();i++){
            JSONObject displayJson = (JSONObject) displayJsonArr.get(i);
            String size = displayJson.getString("size");
            int media_id = Integer.valueOf(displayJson.getString("media_id"));
            JSONObject impressionJson = new JSONObject();

            if(displayJson.has("ads")){
                Object adsObj = displayJson.get("ads");
                if(adsObj instanceof Integer){
                    impressionJson.put("ads",Integer.valueOf(displayJson.getString("ads")));
                }
            }


            if(MEDIA_BANNER ==media_id &&("320*50".equals(size) || "320x50".equals(size))){
               // impressionJson.put("slotid",slotId320);
                impressionJson.put("slotid",1);
            }else if(MEDIA_BANNER ==media_id && ("640*100".equals(size) || "640x100".equals(size))){
                //impressionJson.put("slotid",slotId640);
                impressionJson.put("slotid",2);
            }else {
                //Unavailable Size
                logger.error("size is incorrect:"+size);
            }
            impressionJsonArray.add(i,impressionJson);
        }

        appoachJson.put("impression",impressionJsonArray);

        JSONObject deviceJson = new JSONObject();
        String osName = jsonObject.getJSONObject("os").getString("name");
        if(osName.equalsIgnoreCase("Android")){
            JSONObject androidJson = new JSONObject();

            if(jsonObject.has("android") &&jsonObject.getJSONObject("android").has("imei") ){
                String imei = jsonObject.getJSONObject("android").getString("imei");
                androidJson.put("imei",imei);
                deviceJson.put("android",androidJson);
            }
        }else {
            JSONObject iosJson = new JSONObject();
            if(jsonObject.has("ios") &&jsonObject.getJSONObject("ios").has("idfa") ) {
                String idfa = jsonObject.getJSONObject("ios").getString("idfa");
                iosJson.put("idfa",idfa);
                deviceJson.put("ios",iosJson);
            }
        }

        deviceJson.put("ip",ipAddr);
        appoachJson.put("device",deviceJson);
        return appoachJson;
    }



    public static void main(String[] args){
        JSONObject jsonObj = new JSONObject();

        JSONArray displayJsonArrObj = new JSONArray();
        JSONObject displayJsonObj = new JSONObject();
        displayJsonObj.put("media_id",1);
        displayJsonObj.put("size","320*50");
        //displayJsonObj.put("ads",1);
        displayJsonArrObj.add(0,displayJsonObj);
        jsonObj.put("display",displayJsonArrObj);

        JSONObject deviceJson = new JSONObject();
        deviceJson.put("imei","861602037165298");
        jsonObj.put("android",deviceJson);

        JSONObject osObj = new JSONObject();
        osObj.put("name","Android");
        osObj.put("version","7.0");
        jsonObj.put("os",osObj);

        jsonObj.put("imsi","460011875617090");
        jsonObj.put("network","wifi");

        JSONObject gpsJsonObj = new JSONObject();
        gpsJsonObj.put("lat",12.9921);
        gpsJsonObj.put("lng",29.222);
        jsonObj.put("gps",gpsJsonObj);



        jsonObj.put("ip","112.65.145.179");
        jsonObj.put("model","iphone7");
        jsonObj.put("pkgname","com.qq.wechat");
        jsonObj.put("sdk_ver","1.0");

        /*
        JSONObject gpsJsonObj = new JSONObject();
        gpsJsonObj.put("lat",123.9999);
        gpsJsonObj.put("lng",99.222);
        jsonObj.put("gps",gpsJsonObj);
        */


        System.out.println("Request="+jsonObj);

        AppcoachAction action = new AppcoachAction();
        action.logger.info("Main request data ="+jsonObj);


        //JSONObject response = HttpUtil.postJson("http://27.115.67.239:28082/dsp/getAds",jsonObj);

        JSONObject response = HttpUtil.postJson("https://127.0.0.1:8443/dsp/appcoach/getAds",jsonObj,null);

        //JSONObject response = HttpUtil.postJson("http://127.0.0.1:8080/dsp/getAds",jsonObj);

        System.out.println("DataValidate="+action.DataValidate(jsonObj));
        System.out.println("data="+action.Transfer2AppcoachJson(jsonObj,"112.65.145.179"));

        //HttpUtil.postJson("http://127.0.0.1:8080/getAds",jsonObj);
        System.out.println("response111="+response);

    }



}
